/*
 * @Description:用户路由
 * @Author: maskMan
 * @LastEditTime: 2025-03-12 12:45:58
 */
import Joint from "../mongo/joint";
import Mondb from "../mongo/mondb";
import { Table } from "../mongo/struct";
import { checkAndGetTaskData, createTargetData, getWeightScore } from "../public/gameApp";
import { resSend } from "../public/httpServe";
import { NTarget } from "../types/share";
const express = require("express");
const router = express.Router();
/**获取用户信息 */
router.get("/getUserInfo", async (req: any, res: any) => {
  try {
    const { account, id, loginCount } = req.auth;
    if (!account || !id) {
      console.log("getUserInfo非法请求", req.body, req.auth);
      return resSend(res, null, false, "非法请求");
    }
    const user: any = await Mondb.findOneData(Table.user, { account });
    if (!user) {
      console.log("getUserInfo用户不存在", req.body);
      return resSend(res, null, false, "参数不正确");
    }
    if (loginCount != user.loginCount) {
      console.log("getUserInfo重复登录", req.body);
      return resSend(res, { offLine: true }, false, "账号在其他地方已登陆");
    }
    const send = {
      age: user.age,
      referrer: user.referrer || "",
      coins: user.coins,
      points: user.points,
      lastTime: user.lastTime,
      endTime: user.endTime,
      vipLevel: user.vipLevel,
      name: user.name
    };
    return resSend(res, send, true, "获取信息成功");
  } catch (error) {
    console.error("getUserInfo系统错误", req, error);
    return resSend(res, null, false, "系统错误");
  }
});
//用户修改信息
router.post("/modifyUser", async (req, res) => {
  try {
    const { password, newPassword, age } = req.body;
    const { account, id } = req.auth;
    if (!account || !id) {
      console.log("modifyUser非法请求", req.body, req.auth);
      return resSend(res, null, false, "非法请求");
    }
    if (!password) {
      console.log("modifyUser参数不正确", req.body);
      return resSend(res, null, false, "参数不正确");
    }
    if (!newPassword && !age) {
      console.log("modifyUser参数不正确1", account, password, newPassword, age);
      return resSend(res, null, false, "参数不正确");
    }
    const result = await Joint.modifyUser({ account, password, newPassword, age });
    if (!result) {
      console.log("modifyUser修改信息失败", account, password, newPassword, age);
      return resSend(res, null, false, "修改信息失败");
    }
    const sd = {};
    if (age) {
      sd["age"] = age;
    }
    return resSend(res, sd, true, "修改信息成功");
  } catch (error) {
    console.error("modifyUser系统错误", req, error);
    return resSend(res, null, false, "系统错误");
  }
});
//用户认证
router.get("/userAuth", async (req, res) => {
  try {
    const { password } = req.query;
    const { account, id, loginCount } = req.auth;
    if (!account || !id) {
      console.log("userAuth非法请求", req.query, req.auth);
      return resSend(res, null, false, "非法请求");
    }
    if (!password) {
      console.log("userAuth参数不正确", req.query);
      return resSend(res, null, false, "参数不正确");
    }
    const result = await Joint.userAuth({ account, password });
    if (!result) {
      console.log("userAuth认证失败", account, password);
      return resSend(res, null, false, "认证失败");
    }
    if (loginCount != result.loginCount) {
      console.log("userAuth重复登录", req.body);
      return resSend(res, { offLine: true }, false, "账号在其他地方已登陆");
    }
    return resSend(res, result, true, "认证成功");
  } catch (error) {
    console.error("userAuth系统错误", req, error);
    return resSend(res, null, false, "系统错误");
  }
});
//获取用户小目标数据
router.get("/getTargetData", async (req, res) => {
  try {
    const { account, id, loginCount } = req.auth;
    if (!account || !id) {
      console.log("getTargetData非法请求", req.query, req.auth);
      return resSend(res, null, false, "非法请求");
    }
    const user: any = await Mondb.findOneData(Table.user, { account });
    if (loginCount != user?.loginCount) {
      console.log("getTargetData重复登录", req.body);
      return resSend(res, { offLine: true }, false, "账号在其他地方已登陆");
    }
    const retData = await checkAndGetTaskData(account, user.vipLevel);
    if (retData) {
      console.log("getTargetData获取成功", account, req.auth);
      return resSend(res, { itemData: retData.itemData, taskList: retData.taskList }, true, "获取成功");
    }
    console.log("getTargetData获取失败", account);
    return resSend(res, null, true, "获取数据失败");
  } catch (error) {
    console.error("userAuth系统错误", req, error);
    return resSend(res, null, false, "系统错误");
  }
});
//创建用户小目标数据
router.post("/createMyTarget", async (req, res) => {
  try {
    const { account, id, loginCount } = req.auth;
    const createData: NTarget.Create = req.body;
    if (!account || !id) {
      console.log("createMyTarget非法请求", req.query, req.auth);
      return resSend(res, null, false, "非法请求");
    }
    if (!createData) {
      console.log("createMyTarget非法请求", req.query, req.auth);
      return resSend(res, null, false, "非法请求");
    }
    const user = await Joint.getUserInfo(account, "age", "loginCount", "vipLevel");
    if (!user) {
      console.log("createMyTarget用户不存在", req.query, req.auth);
      return resSend(res, null, false, "非法请求");
    }
    if (loginCount != user?.loginCount) {
      console.log("createMyTarget重复登录", req.body);
      return resSend(res, { offLine: true }, false, "账号在其他地方已登陆");
    }
    const result = createTargetData(createData, user.age);
    if (result) {
      const resultValue = await Joint.createTarget(account, createData, result.itemData, result.taskList);
      if (resultValue) {
        const taskData = await checkAndGetTaskData(account, user.vipLevel);
        if (taskData) {
          return resSend(res, { itemData: taskData.itemData, taskList: taskData.taskList }, true, "创建失败");
        }
      }
      return resSend(res, null, false, "创建失败");
    }
    console.log("createMyTarget创建失败", account);
    return resSend(res, null, false, "创建失败");
  } catch (error) {
    console.error("createMyTarget系统错误", req, error);
    return resSend(res, null, false, "系统错误");
  }
});
//删除用户小目标数据
router.get("/delTargetData", async (req, res) => {
  try {
    const { account, id } = req.auth;
    if (!account || !id) {
      console.log("delTargetData非法请求", req.query, req.auth);
      return resSend(res, null, false, "非法请求");
    }
    const del = await Joint.delTargetData(account);
    if (del) {
      console.log("delTargetData删除成功", account);
      return resSend(res, true, true, "删除成功");
    }
    console.log("delTargetData删除失败", account);
    return resSend(res, false, true, "删除成功");
  } catch (error) {
    console.error("delTargetData系统错误", req, error);
    return resSend(res, null, false, "系统错误");
  }
});
//更新小目标报告记录
router.post("/updateTargetReport", async (req, res) => {
  try {
    const { account, id, loginCount } = req.auth;
    if (!account || !id) {
      console.log("updateTargetReport非法请求", req.query, req.auth);
      return resSend(res, null, false, "非法请求");
    }
    const { task, record, itemData } = req.body;
    if (!task || !record || !itemData) {
      console.log("updateTargetReport非法请求", req.query, req.auth);
      return resSend(res, null, false, "非法请求");
    }
    const user: any = await Mondb.findOneData(Table.user, { account });
    if (loginCount != user?.loginCount) {
      console.log("updateTargetReport重复登录", req.body);
      return resSend(res, { offLine: true }, false, "账号在其他地方已登陆");
    }
    const retValue = await Joint.updateTargetData(account, task, itemData, record);
    if (!retValue) {
      console.log("updateTargetData更新保存进度失败", account);
      return resSend(res, null, false, "更新失败");
    }
    const result = await Joint.updateTargetReport(account, record, itemData, task);
    if (!result) {
      console.log("updateTargetReport更新记录失败", account);
      return resSend(res, null, false, "更新失败");
    }
    return resSend(res, true, true, "更新成功");
  } catch (error) {
    console.error("updateTargetReport系统错误", req, error);
    return resSend(res, null, false, "系统错误");
  }
});
//获取用户小目标训练报告
router.get("/getNewDiary", async (req, res) => {
  try {
    const { account, id } = req.auth;
    if (!account || !id) {
      console.log("getNewDiary非法请求", req.query, req.auth);
      return resSend(res, null, false, "非法请求");
    }
    const { dateIndex } = req.query;
    const retData = await Joint.getTargetDiary(account, dateIndex);
    if (retData) {
      console.log("getNewDiary获取成功", account, req.auth);
      return resSend(res, retData, true, "获取成功");
    }
    console.log("getNewDiary获取失败", account);
    return resSend(res, null, true, "获取数据失败");
  } catch (error) {
    console.error("getNewDiary系统错误", req, error);
    return resSend(res, null, false, "系统错误");
  }
});
//领取小目标奖励
router.post("/getTargetReword", async (req, res) => {
  try {
    const { account, id, loginCount } = req.auth;
    if (!account || !id) {
      console.log("getTargetReword非法请求", req.query, req.auth);
      return resSend(res, null, false, "非法请求");
    }
    const { task } = req.body;
    if (!task) {
      console.log("getTargetReword非法请求", req.query, req.auth);
      return resSend(res, null, false, "非法请求");
    }
    const user: any = await Mondb.findOneData(Table.user, { account });
    if (loginCount != user?.loginCount) {
      console.log("getTargetReword重复登录", req.body);
      return resSend(res, { offLine: true }, false, "账号在其他地方已登陆");
    }
    if (task.markStatus == -1 && task.completed == false) {
      const retData = await Joint.updateTargetReword(account, task);
      console.log(retData);
      if (retData) {
        console.log("getTargetReword获取成功", account, req.auth);
        return resSend(res, retData, true, "奖励领取成功");
      }
    }
    console.log("getTargetReword获取失败", account);
    return resSend(res, null, true, "领取奖励失败");
  } catch (error) {
    console.error("getReword系统错误", req, error);
    return resSend(res, null, false, "系统错误");
  }
});
//获取金币奖励
router.post("/getRewordCoins", async (req, res) => {
  try {
    const { account, id, loginCount } = req.auth;
    if (!account || !id) {
      console.log("upCoins非法请求", req.query, req.auth);
      return resSend(res, null, false, "非法请求");
    }
    let { score, costTime, fixTime, errCount, addCoins } = req.body;
    if (costTime && fixTime) {
      const time = Math.floor(fixTime / 60);
      if (!addCoins) {
        addCoins = 0;
      }
      const coins = getWeightScore(score, errCount || 0, time, costTime);
      let addValue;
      if (coins >= 0) {
        addValue = score == -1 ? addCoins : coins + addCoins;
        const ret = await Joint.upUserCoins(account, addValue);
        if (ret) {
          if (loginCount != ret.loginCount) {
            console.log("getRewordCoins重复登录", req.body);
            return resSend(res, { offLine: true }, false, "账号在其他地方已登陆");
          }
          let text = score == -1 ? addValue : "";
          if (addCoins >= 0 && score >= 0) {
            text += addCoins;
          }
          if (coins >= 0 && score >= 0) {
            if (text) {
              text += "+" + coins;
            } else {
              text = coins;
            }
          }
          return resSend(res, coins + addCoins, true, score == -1 ? `获得${addValue}金币` : `获得${addValue}金币奖励(${text})`);
        }
      }
      return resSend(res, null, false, "奖励失败");
    }
    console.log("upCoins获取失败", account);
    return resSend(res, null, true, "更新金币失败");
  } catch (error) {
    console.error("upCoins系统错误", req, error);
    return resSend(res, null, false, "系统错误");
  }
});
//购买商品
router.post("/buyShop", async (req, res) => {
  try {
    const { account, id, loginCount } = req.auth;
    if (!account || !id) {
      console.log("buyShop非法请求", req.body, req.auth);
      return resSend(res, null, false, "非法请求");
    }
    const { buyInfo, shopType } = req.body;
    if (!buyInfo || !shopType) {
      console.log("buyShop参数不正确", req.body);
      return resSend(res, null, false, "参数不正确");
    }
    const user: any = await Mondb.findOneData(Table.user, { account });
    if (loginCount != user?.loginCount) {
      console.log("buyShop重复登录", req.body);
      return resSend(res, { offLine: true }, false, "账号在其他地方已登陆");
    }
    const textList = { baojian: "视力保健", study: "思维益智", shuji: "学习阅读", game: "儿童玩具", dong: "养成宠物" };
    const result = await Joint.buyShop(account, textList[shopType], buyInfo);
    if (!result) {
      console.log("buyShop购买失败", account, buyInfo, shopType);
      return resSend(res, null, true, "购买失败");
    }
    return resSend(res, result, true, "购买成功");
  } catch (error) {
    console.error("buyShop系统错误", req, error);
    return resSend(res, null, false, "系统错误");
  }
});
//查看用户兑换记录
router.get("/getUserPayRecord", async (req, res) => {
  try {
    const { account, id } = req.auth;
    if (!account || !id) {
      console.log("getUserPayRecord非法请求", req.query, req.auth);
      return resSend(res, null, false, "非法请求");
    }
    let { data } = req.query;
    if (data == "completed") {
      const list = await Mondb.findManyData(Table.shopRecord, { status: "已完成" });
      return resSend(res, list, true, "获取列表成功");
    } else if (data == "curr") {
      const list = await Mondb.findManyData(Table.shopRecord, { status: { $ne: "已完成" } });
      return resSend(res, list, true, "获取列表成功");
    }
    console.log("getUserPayRecord获取失败", account);
    return resSend(res, null, false, "获取列表失败");
  } catch (error) {
    console.error("getUserPayRecord系统错误", req, error);
    return resSend(res, null, false, "系统错误");
  }
});
export default router;
